/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2024-04-28 17:31:02
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-29 12:56:11
 * @FilePath: /yt-devops/lib/pages/amap/widget/google_map_widget.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/amap_poi.dart';
import 'package:yt_devops/pages/amap/map_const_config.dart';
import 'package:yt_devops/services/map/map_services.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/func_utils.dart';

class GoogleMapWidget extends StatefulWidget {
  final LatLng position;

  final Function(AmapPoi)? onPositionShow;
  const GoogleMapWidget(
      {super.key,
      this.position = const LatLng(39.909187, 116.397451),
      this.onPositionShow});

  @override
  State<GoogleMapWidget> createState() => GoogleMapWidgetState();
}

class GoogleMapWidgetState extends State<GoogleMapWidget> {
  late GoogleMapController mapController;

  HttpClient httpClient = HttpClient();

  late LatLng _position;

  @override
  void initState() {
    _position = widget.position;
    super.initState();
  }

  Set<Marker> get myPositionMarker => {
        Marker(
          markerId: const MarkerId('my_position'),
          position: _position,
          onDrag: (value) => geoLatng(value),
        )
      };

  @override
  Widget build(BuildContext context) {
    return GoogleMap(
      initialCameraPosition: CameraPosition(target: widget.position, zoom: 16),
      myLocationEnabled: true,
      markers: myPositionMarker,
      onCameraMove: (position) => onCameraMove(position),
      onTap: (argument) => onMapClick(argument),
      onMapCreated: (controller) => onMapCreate(controller),
    );
  }

  onMapCreate(GoogleMapController controller) {
    mapController = controller;
  }

  Future<AmapPoi?> geoLatng(LatLng latLng) async {
    AmapPoi? poi;
    showLoading();
    poi = await MapServices.geoGoogleLatng(
        context, LatLngModel(latLng.latitude, latLng.longitude));

    dismissLoading();

    return poi;
  }

  onCameraMove(CameraPosition position) {}

  onMapClick(LatLng latLng) async {
    setState(() {
      _position = latLng;
    });
    await mapController.moveCamera(CameraUpdate.newLatLngZoom(latLng, 16));
    var poi = await geoLatng(latLng);
    if (poi != null) {
      widget.onPositionShow?.call(poi);
    }
  }

  Future searchAroundAddress(String keyword) async {
    List<AmapPoi>? pois;
    var request = await httpClient.getUrl(Uri.tryParse(
        'https://maps.googleapis.com/maps/api/place/textsearch/json?language=${Get.locale?.languageCode}&query= $keyword&key=${MapConstConfig.googleApiKey}')!);

    final response = await request.close();

    try {
      if (response.statusCode == 200) {
        String responseBody = await response.transform(utf8.decoder).join();
        var data = json.decode(responseBody);
        if (data?['results']?.isNotEmpty == true) {
          pois = data!['results']
              .map<AmapPoi>(
                (e) => AmapPoi(
                    name: e['name'],
                    latitude: e['geometry']['location']['lat'],
                    longitude: e['geometry']['location']['lng'],
                    formattedAddress: e['formatted_address']),
              )
              .toList();
        }
      }
    } catch (e) {
      showError(e.toString());
    } finally {
      // dismissLoading();
    }
    showSearchResult(pois!);
  }

  showSearchResult(List<AmapPoi> pois) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        padding: EdgeInsets.fromLTRB(20.w, 20.h, 20.w, 16.h),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.w),
          color: Colors.white,
        ),
        height: 383.h,
        child: ListView.separated(
          itemCount: pois.length,
          itemBuilder: (context, index) => InkWell(
            onTap: () async {
              showTargetPosition(pois[index]);
            },
            child: Column(children: <Widget>[
              Container(
                margin: const EdgeInsets.only(top: 8, bottom: 5, left: 10),
                child: Row(
                  children: <Widget>[
                    const Icon(
                      Icons.place,
                      size: 20.0,
                    ),
                    Text(pois[index].name ?? '',
                        style: const TextStyle(
                          fontSize: 16,
                        ))
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 5, bottom: 5, left: 18),
                alignment: Alignment.centerLeft,
                child: Text(
                  pois[index].formattedAddress ?? '',
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xFF646464),
                  ),
                ),
              ),
            ]),
          ),
          separatorBuilder: (BuildContext context, int index) {
            return const Divider(color: Colour.dividerColor);
          },
        ),
      ),
    );
  }

  Future showTargetPosition(AmapPoi poi) async {
    setState(() {
      _position = LatLng(
        poi.latitude,
        poi.longitude,
      );
    });
    await mapController.moveCamera(CameraUpdate.newLatLngZoom(_position, 16));

    widget.onPositionShow?.call(poi);
  }
}
